/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista.users;

import config.SConfig;
import controlador.users.UserSession;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import modelo.DetalleOrdenDeCompra;
import modelo.User;
import util.HashUtil;
import util.HibernateUtil;
import util.SwingPanel;
import vista.gui.ComboCellRenderer;

/**
 *
 * @author Administrador
 */
public class ABMUsers extends javax.swing.JInternalFrame {

    private int idUser;
    private User updateUser;
    private static final String[] urlAvatars = {
        "/res/avatares/1.png",
        "/res/avatares/2.png",
        "/res/avatares/3.png",
        "/res/avatares/4.png",
        "/res/avatares/5.png",
        "/res/avatares/6.png",
        "/res/avatares/7.png", 
        "/res/avatares/8.png", 
        "/res/avatares/9.png", 
        "/res/avatares/10.png", 
        "/res/avatares/11.png", 
        "/res/avatares/12.png", 
        "/res/avatares/13.png", 
        "/res/avatares/14.png", 
        "/res/avatares/15.png" 
    };

    /**
     * Modificacion de un usuario, SOLO YO MISMO PUEDO MODIFICARME. Un ADMIN,
     * puede cambiar el estado !!!
     *
     * @param idUser
     */
    public ABMUsers(int idUser) {
        initComponents();
        cargarUsuario(idUser);
        llenarComboEstado();
        llenarComboImagenes();
        initDatos();
    }

    /**
     * Creo directamente un usuario
     */
    public ABMUsers() {
        initComponents();
        llenarComboEstado();
        llenarComboImagenes();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        jLabel1 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        lblTituloPass = new javax.swing.JLabel();
        txtPass = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        cmbEstado = new javax.swing.JComboBox();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        cmbImagen = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        optAdmin = new javax.swing.JRadioButton();
        optSimpleUser = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        ck1 = new javax.swing.JCheckBox();
        ck2 = new javax.swing.JCheckBox();
        ck3 = new javax.swing.JCheckBox();
        ck4 = new javax.swing.JCheckBox();
        ck5 = new javax.swing.JCheckBox();
        ck6 = new javax.swing.JCheckBox();
        ck7 = new javax.swing.JCheckBox();

        jButton4.setText("jButton4");

        jScrollPane1.setViewportView(jEditorPane1);

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Administración de Usuarios");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Nombre de Usuario:");

        lblTituloPass.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblTituloPass.setText("Contraseña:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Estado:");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/block.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/save_upload.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Permisos del Usuario"));

        buttonGroup1.add(optAdmin);
        optAdmin.setText("Administrador");
        optAdmin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optAdminActionPerformed(evt);
            }
        });

        buttonGroup1.add(optSimpleUser);
        optSimpleUser.setSelected(true);
        optSimpleUser.setText("Usuario Simple");
        optSimpleUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optSimpleUserActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de los permisos"));

        ck1.setText("Módulo de Compras");

        ck2.setText("Módulo de Recursos Humanos");

        ck3.setText("Módulo de Comercialización");

        ck4.setText("Módulo de Cotización de Obra");

        ck5.setText("Módulo de Planificación de Obra");

        ck6.setText("Módulo de Ejecución de Obra");
        ck6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ck6ActionPerformed(evt);
            }
        });

        ck7.setText("Módulo de Control de Obra");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ck2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ck3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ck4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ck5, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(ck7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ck6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ck1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(ck1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ck7))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(optAdmin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(optSimpleUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(optAdmin)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optSimpleUser)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmbImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtUserName)
                            .addComponent(lblTituloPass, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtPass)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cmbEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblTituloPass)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cmbImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnGuardar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

        String mensaje;
        if (this.updateUser == null) {
            mensaje = "¿Está seguro que desea crear el nuevo Usuario?";
        } else {
            mensaje = "¿Está seguro que desea modificar el Usuario?";
        }

        int n = JOptionPane.showConfirmDialog(
                new JFrame(),
                mensaje,
                "Atencion!",
                JOptionPane.YES_NO_OPTION);

        if (n == JOptionPane.YES_OPTION) {

            if (validar()) {
                if (guardar()) {
                    String mensajeExito;
                    if (this.updateUser == null) {
                        mensajeExito = "El nuevo usuario del sistema se creó exitosamente!";
                    } else {
                        mensajeExito = "El usuario del sistema se modificó exitosamente!";
                    }
                    MostrarMensaje(JOptionPane.INFORMATION_MESSAGE, "Exito!", mensajeExito);
                    this.dispose();
                } else {
                    MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error!", "Se produjo un error al intentar guardar el usuario");
                }
            }

        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void ck6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ck6ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ck6ActionPerformed

    private void optSimpleUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optSimpleUserActionPerformed
        System.out.println("Selecciono Simple");
        activarChecksDePermisos(true);
    }//GEN-LAST:event_optSimpleUserActionPerformed

    private void optAdminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optAdminActionPerformed
        System.out.println("Selecciono Administrador");
        activarChecksDePermisos(false);
    }//GEN-LAST:event_optAdminActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JCheckBox ck1;
    private javax.swing.JCheckBox ck2;
    private javax.swing.JCheckBox ck3;
    private javax.swing.JCheckBox ck4;
    private javax.swing.JCheckBox ck5;
    private javax.swing.JCheckBox ck6;
    private javax.swing.JCheckBox ck7;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JComboBox cmbImagen;
    private javax.swing.JButton jButton4;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTituloPass;
    private javax.swing.JRadioButton optAdmin;
    private javax.swing.JRadioButton optSimpleUser;
    private javax.swing.JPasswordField txtPass;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

    /**
     * Llena el combo de Estado
     */
    private void llenarComboEstado() {
        cmbEstado.removeAllItems();
        cmbEstado.addItem(User.ESTADO_ALTA);
        cmbEstado.addItem(User.ESTADO_BAJA);

        // If Modificacion (Alto Hardcode)
        if (this.updateUser != null) {
            if (User.ESTADO_ALTA.equals(this.updateUser.getEstado())) {
                cmbEstado.setSelectedIndex(0);
            } else {
                cmbEstado.setSelectedIndex(1);
            }
        }
    }

    private void llenarComboImagenes() {
        cmbImagen.removeAllItems();
        cmbImagen.setRenderer(new ComboCellRenderer());

        for (int i = 0; i < urlAvatars.length; i++) {
            String urlImagen = urlAvatars[i];
            JLabel avatar = new JLabel();
            avatar.setIcon(new javax.swing.ImageIcon(getClass().getResource(urlImagen)));
            cmbImagen.addItem(avatar);
        }

        // If modificacion, selecciono
        if (this.updateUser != null) {
            String urlFoto = this.updateUser.getUrlFoto();
            for (int i = 0; i < urlAvatars.length; i++) {
                String avatar = urlAvatars[i];
                if (avatar.equals(urlFoto)) {
                    cmbImagen.setSelectedIndex(i);
                }
            }
        }
    }

    /**
     * Muestra un mensaje
     *
     * @param tipo
     * @param titulo
     * @param mensaje
     */
    public void MostrarMensaje(int tipo, String titulo, String mensaje) {
        JOptionPane.showMessageDialog(this.getParent(), mensaje, titulo, tipo);
    }

    private boolean validar() {

        boolean validado = true;
        StringBuilder msg = new StringBuilder("<HTML>Para continuar, verifique:");

        if (txtUserName.getText().isEmpty()) {
            msg.append("<br>- El <b>Nombre de Usuario</b> no esté vacío.");
            validado = false;
        }

        if (this.updateUser == null && txtPass.getPassword().length == 0) {
            msg.append("<br>- La <b>Contraseña ingresara</b> no puede ser vacia.");
            validado = false;
        }

        if (this.updateUser == null && txtPass.getPassword().length < 6) {
            msg.append("<br>- La <b>Contraseña ingresara</b> debe tener <b>6</b> o más caracteres.");
            validado = false;
        }

        // Si modifico un usuario, solo puedo modificar el mio, salvo que sea ADMIN
        User currentLogin = UserSession.getInstance().getUsuarioLogeado();
        if (this.updateUser != null && currentLogin.getId()!=this.updateUser.getId() && !currentLogin.isIsAdmin()){
            // Si modifico y no soy yo y no tengo permisos de Admin
            msg.append("<br>- No tenes <b>Permisos</b> para modificar este usuario, Comunicate con el Administrador!");
            validado = false;
        }
        
        if (!validado) {
            MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error de Validación!", msg.toString());
        }
        
        return validado;

    }

    private boolean guardar() {
        User usuario = null;
        if (this.updateUser == null) {
            // Nuevo Usuario
            usuario = new User();
        } else {
            // Update
            usuario = this.updateUser;
        }

        usuario.setUsuario(txtUserName.getText());

        // Cambio contraseña o no
        if (this.updateUser == null) {
            // Estoy Creando
            String encPass = HashUtil.encriptarString(HashUtil.ENCRYPT_SHA256, new String(txtPass.getPassword()));
            usuario.setPassword(encPass);
        } else {
            if (!txtPass.getText().isEmpty()) {
                // Quiere cambiar la contraseña
                JPasswordField pf = new JPasswordField();
                int okCxl = JOptionPane.showConfirmDialog(null, pf,
                        "Ingrese su antigua contraseña",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.PLAIN_MESSAGE);

                if (okCxl == JOptionPane.OK_OPTION) {
                    String oldPassword = new String(pf.getPassword());
                    // La antigua contraseña coincide???
                    String oldEncPass = HashUtil.encriptarString(HashUtil.ENCRYPT_SHA256, oldPassword);
                    if (oldEncPass.equals(this.updateUser.getPassword())) {
                        // Coincide ... Cambio
                        String encPass = HashUtil.encriptarString(HashUtil.ENCRYPT_SHA256, new String(txtPass.getPassword()));
                        usuario.setPassword(encPass);
                    } else {
                        // No coincide ... aviso
                        MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error!", "La contraseña ingresada no coincide con su antigua contraseña");
                        return false;
                    }
                }
            }
        }

        usuario.setUrlFoto(urlAvatars[cmbImagen.getSelectedIndex()]);
        usuario.setEstado((String) cmbEstado.getSelectedItem());

        if (optAdmin.isSelected()) {
            usuario.setIsAdmin(true);
        } else {
            usuario.setIsAdmin(false);
            // Cargo los permisos
            String permisos = "";
            if(ck1.isSelected()){
                permisos += User.PERMISO_MODULO_COMPRAS;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck2.isSelected()){
                permisos += User.PERMISO_MODULO_RRHH;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck3.isSelected()){
                permisos += User.PERMISO_MODULO_COMERCIALIZACION;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck4.isSelected()){
                permisos += User.PERMISO_MODULO_COTIZACION;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck5.isSelected()){
                permisos += User.PERMISO_MODULO_PLANIFICACION;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck6.isSelected()){
                permisos += User.PERMISO_MODULO_EJECUCION;
                permisos += User.PERMISO_SEPARADOR;
            }
            if(ck7.isSelected()){
                permisos += User.PERMISO_MODULO_CONTROL;
            } 
            usuario.setPermisos(permisos);
        }

        if (usuario != null) {
            try {
                HibernateUtil.beginTransaction();
                HibernateUtil.getSession().saveOrUpdate(usuario);
                HibernateUtil.commitTransaction();
                return true;
            } catch (Exception e) {
                HibernateUtil.rollbackTransaction();
                MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error!", "Se produjo un error al Generar y Guardar el Usuario\n" + e.getMessage());
                return false;
            }
        } else {
            MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error!", "Se produjo un error grave al crear el usuario");
        }

        return false;
    }

    /**
     * Carga el usuario
     *
     * @param idUser
     */
    private void cargarUsuario(int idUser) {
        try {
            HibernateUtil.beginTransaction();
            this.updateUser = (User) HibernateUtil.getSession().load(User.class, idUser);
            HibernateUtil.commitTransaction();
        } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
            MostrarMensaje(JOptionPane.ERROR_MESSAGE, "Error!", "Se produjo un error al cargar el Usuario\n" + e.getMessage());
            return;
        }
    }

    private void initDatos() {
        if (this.updateUser != null) {
            txtUserName.setText(this.updateUser.getUsuario());
            txtPass.setText("");
                       
            // Veo si puedo modificar al usuario
            if(!UserSession.getInstance().isAdmin()){
                optAdmin.setEnabled(false);
                optSimpleUser.setEnabled(false);
                activarChecksDePermisos(false);
                cmbEstado.setEnabled(false);
                
                // Solo dejo cambiar la contraseña al propio usuario
                int idUserLoged = UserSession.getInstance().getUsuarioLogeado().getId();
                if(idUserLoged!=this.updateUser.getId()){
                    txtPass.setEnabled(false);
                    txtUserName.setEnabled(false);
                    btnGuardar.setEnabled(false);
                }
                
            }
            
            if (this.updateUser.isIsAdmin()) {
                optAdmin.setSelected(true);
                activarChecksDePermisos(false);
            } else {
                optSimpleUser.setSelected(true);
                // Lleno los permisos que tiene
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_COMPRAS)){
                    ck1.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_RRHH)){
                    ck2.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_COMERCIALIZACION)){
                    ck3.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_COTIZACION)){
                    ck4.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_PLANIFICACION)){
                    ck5.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_EJECUCION)){
                    ck6.setSelected(true);
                }
                if(this.updateUser.tienePermisos(User.PERMISO_MODULO_CONTROL)){
                    ck7.setSelected(true);
                }                
            }
            lblTituloPass.setText("Cambiar Contraseña:");
        }
    }

    private void activarChecksDePermisos(boolean b) {
        ck1.setEnabled(b);
        ck2.setEnabled(b);
        ck3.setEnabled(b);
        ck4.setEnabled(b);
        ck5.setEnabled(b);
        ck6.setEnabled(b);
        ck7.setEnabled(b);
    }
}
